<template>
  <div class="flex h-full cate-left">
    <div class="w-[256px] h-full bg-white mr-[16px]">
      <div :class="TITLE_CLASS">
        <div class="flex items-center w-full">
          <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
          <div class="text-[#242930] text-sm ml-[10px]">
            {{ t("task_detail.form.category_list") }}
          </div>
        </div>
      </div>
      <div class="px-[20px] py-[16px] h-[calc(100%_-_54px)]">
        <el-input
          v-model="category"
          :prefix-icon="useRenderIcon('iconamoon:search-light')"
          :placeholder="t('task_detail.form.enter_category_name')"
          @input="handleInput"
        />
        <el-scrollbar class="mt-4 scroll-height">
          <el-checkbox-group v-model="checkList">
            <div
              v-for="(item, index) in categoryList"
              :key="item.id"
              :class="[
                'striped cate flex items-center justify-between pr-2',
                categoryChoose?.id === item.id ? 'active' : ''
              ]"
              @click="cateClick(item)"
            >
              <!--                <el-checkbox :value="item.id" />-->
              <!-- <div>{{ index + 1 }}、{{ item.name }}</div> -->
              <el-tooltip
                :disabled="item.name.length < 18"
                :content="item.name"
                placement="top"
              >
                <div
                  ref="textContainer"
                  class="truncate"
                  :style="{ maxWidth: '180px' }"
                >
                  <span v-if="item.name != '全部'"
                    >{{ category ? index + 1 : index }}、</span
                  >{{ item.name }}
                </div>
              </el-tooltip>
              <div
                v-if="item.subId != 1 && item.subId != 2 && item.name != '全部'"
                class="flex"
              >
                <i
                  class="text-[--el-color-primary] hover:text-[#8fb6ee]"
                  @click="editCate(item)"
                >
                  <IconifyIconOnline icon="ep:edit-pen" />
                </i>
                <i
                  class="text-[--el-color-primary] hover:text-[#8fb6ee] ml-2"
                  @click="delCate(item)"
                >
                  <IconifyIconOnline icon="ep:delete" />
                </i>
              </div>
            </div>
          </el-checkbox-group>
        </el-scrollbar>
        <el-button
          class="add-btn"
          color="#F5F9FF"
          size="small"
          @click="addCate"
        >
          <FontIcon icon="icon-plus2" />
          &nbsp;{{ t("task_detail.form.add_category") }}
        </el-button>
      </div>
    </div>

    <div class="w-[calc(100%_-_272px)] h-full bg-white">
      <div :class="TITLE_CLASS">
        <div class="flex items-center">
          <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
          <div class="text-[#242930] text-sm ml-[10px]">
            {{ t("task_detail.form.task_list") }} - {{ route.query?.name }}
          </div>
        </div>

        <div class="flex-grow flex items-center justify-end">
          <AuForm
            ref="formRef"
            class="mat-btn"
            :formList="formList"
            @submit="search"
          />
          <el-button
            type="primary"
            class="ml-4"
            @click="actionClick({ key: ACTION_TYPE.TADD, row: null })"
            >{{ t("task_detail.form.add") }}
          </el-button>
        </div>
      </div>
      <div class="h-[calc(100%_-_55px)]">
        <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
          <template #time_default="{ row }">
            <span>{{
              row.reminderType == 1 ? row.singleReminderTime : row.reminderHour
            }}</span>
          </template>
          <template #status_default="{ row }">
            <el-tag :type="row.openStatus === 1 ? 'primary' : 'info'"
              >{{
                row.openStatus === 1
                  ? t("task_detail.form.enabled")
                  : t("task_detail.form.disabled")
              }}
            </el-tag>
          </template>
        </AuTable>
      </div>
    </div>

    <CateModal
      v-model="showCateModal"
      :form-data="cateRow"
      :last-sub-id="lastSubId"
      @confirm="getTaskType"
    />

    <TaskEditModal
      v-model="showTaskModal"
      :form-data="taskRow"
      :taskParam="taskParam"
      :type-list="categoryList"
      @confirm="getMatData"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, onUpdated, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import { ACTION_TYPE, PropDefines } from "@/components/AuTable/type";
import { cloneDeep, useGlobal } from "@pureadmin/utils";
import { BaseProps } from "@/components/AuForm/type";
import { AuForm } from "@/components/AuForm";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRoute, useRouter } from "vue-router";
import CateModal from "./components/CategoryModal.vue";
import {
  taskDel,
  taskGetList,
  TaskListProp,
  taskTypeAdd,
  taskTypeDel,
  taskTypeGetList,
  TaskTypeListProp,
  taskTypeUpd,
  taskUpd
} from "@/api/expiry/task";
import { ElMessage } from "element-plus";
import { REMINDER_LIST } from "@/views/expiry/task/taskTime/constants";
import TaskEditModal from "@/views/expiry/task/taskTime/components/TaskEditModal.vue";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "taskTime"
});

// region 声明ref变量集合
const { t } = useI18n();
const router = useRouter();
const TITLE_CLASS =
  "flex items-center justify-between h-[54px] border-b border-[--autata-border-color] px-[16px]";
const { $storage } = useGlobal<GlobalPropertiesApi>();
const { proxy } = getCurrentInstance();
const route = useRoute();

const category = ref("");
const categoryList = ref([]);
const categoryListRegion = ref([]);
const checkList = ref<number[]>([]);
const categoryChoose = ref<TaskTypeListProp>(null);

const lastSubId = ref(2);

let tableDataSource = [];

const formList = ref<BaseProps[]>([
  {
    type: "input",
    label: "task_detail.form.task_name",
    key: "name",
    span: 14,
    placeholder: "task_detail.form.enter_task_name"
  }
]);
const gridOption = reactive<PropDefines>({
  isServerPage: false,
  showExportBtn: false,
  columns: [
    { field: "name", title: "task_detail.form.task_name" },
    // {
    //   field: "expiryStatus",
    //   title: "效期状态",
    //   slots: { default: "expiry_default" }
    // },
    {
      field: "openStatus",
      title: "task_detail.form.timer_status",
      align: "center",
      slots: { default: "status_default" }
    },
    {
      field: "time",
      title: "task_detail.form.reminder_time",
      align: "center",
      minWidth: 130,
      slots: { default: "time_default" }
    },
    {
      field: "reminderType",
      title: "task_detail.form.single_reminder",
      align: "center",
      formatter({ row }) {
        return row.reminderType == 1
          ? t("task_detail.form.yes")
          : t("task_detail.form.no");
      }
    },
    {
      field: "loopType",
      title: "task_detail.form.repeat_type",
      align: "center",
      formatter({ cellValue, row }) {
        if (row.reminderType == 1) {
          return "/";
        } else {
          const find = REMINDER_LIST(t).find(v => v.value == cellValue);
          return find?.label;
        }
      }
    },
    { field: "note", title: "task_detail.form.task_description" }
  ],
  actions: [ACTION_TYPE.EDIT, ACTION_TYPE.DELETE],
  operateTools: [
    {
      key: ACTION_TYPE.PUTAWAY,
      name: "table.open",
      hiddenHandle: (row: TaskListProp) => {
        return row.openStatus === 1;
      }
    },
    {
      key: ACTION_TYPE.OFFSHELVE,
      name: "table.close",
      hiddenHandle: (row: TaskListProp) => {
        return row.openStatus === 0;
      }
    }
  ],
  topTools: [],
  dataSource: []
});

const showCateModal = ref(false);
const cateRow = ref<TaskTypeListProp>();

const showTaskModal = ref(false);
const taskRow = ref<TaskListProp>();
const taskParam = ref({
  typeId: "",
  subId: "",
  versionId: route.query?.versionId
});
const isTooltipDisabled = ref(true);

const textContainer = ref(null);
// 检测文本是否溢出
const checkOverflow = () => {
  if (textContainer.value) {
    const isOverflow =
      textContainer.value.scrollWidth > textContainer.value.clientWidth;
    isTooltipDisabled.value = !isOverflow;
  }
};

const formRef = ref();
const tableRef = ref();
// endregion

// region 公共方法的集合
const handleInput = () => {
  if (category.value.length > 0) {
    categoryList.value = cloneDeep(categoryListRegion.value).filter(item =>
      item.name.includes(category.value)
    );
  } else {
    categoryList.value = cloneDeep(categoryListRegion.value);
  }
};

async function getMatData() {
  taskGetList({
    size: 0,
    filter: {
      versionId: route.query?.versionId,
      typeId: categoryChoose.value?.id,
      ...formRef.value.getFormData()
    }
  }).then(async res => {
    gridOption.dataSource = res?.data ?? [];
    // tableDataSource = [...matList];
    // cateClick(categoryChoose.value);
  });
}

async function getTaskType() {
  let res = await taskTypeGetList({
    size: 0
  });
  if (!res?.data?.length) {
    await taskTypeAdd({
      name: t("task_detail.form.business_task"),
      note: "",
      subId: 1
    });
    await taskTypeAdd({
      name: t("task_detail.form.closing_task"),
      note: "",
      subId: 2
    });
  } else {
    for (const item of res.data) {
      if (item.name === t("task_detail.form.business_task") && !item.subId) {
        await taskTypeUpd({
          ...item,
          subId: 1
        });
      } else if (
        item.name === t("task_detail.form.closing_task") &&
        !item.subId
      ) {
        await taskTypeUpd({
          ...item,
          subId: 2
        });
      }
    }
  }

  res = await taskTypeGetList({
    size: 0
  });
  lastSubId.value = Number(res.data[res.data.length - 1]?.subId ?? 2);

  categoryList.value = [
    {
      name: "全部",
      id: "",
      subId: ""
    },
    ...(res?.data ?? [])
  ];
  categoryListRegion.value = cloneDeep(categoryList.value);
}

async function init() {
  await getTaskType();
  cateClick(categoryList.value[0]);
}

// endregion

// region 组件事件的集合
const search = () => {
  getMatData();
};

const cateClick = (item: TaskTypeListProp) => {
  categoryChoose.value = item;
  getMatData();
  taskParam.value.typeId = String(item.id);
  taskParam.value.subId = String(item.subId);
};

const editCate = (item: TaskTypeListProp) => {
  showCateModal.value = true;
  cateRow.value = item;
};
const delCate = item => {
  proxy.$auMessageBox
    .confirm(t("task_detail.form.confirm_delete_category"), t("notice.title"))
    .then(() => {
      taskTypeDel({ ids: [item.id] }).then(res => {
        ElMessage({
          message: t("notice.delete_success"),
          type: "success"
        });
        init();
      });
    });
};
const addCate = () => {
  showCateModal.value = true;
  cateRow.value = null;
};

const toPrevPage = () => {
  router.push({
    name: "taskVersion"
  });
};

/**
 * 上架/下架
 * @param row {TaskListProp}
 * @param status {ACTION_TYPE.OFFSHELVE | ACTION_TYPE.PUTAWAY}
 */
const handleUpOrDown = (
  row: TaskListProp,
  status: ACTION_TYPE.OFFSHELVE | ACTION_TYPE.PUTAWAY
) => {
  const statusText =
    status === ACTION_TYPE.OFFSHELVE ? t("table.close") : t("table.open");
  const msg = t("task_detail.form.confirm_status_change", {
    status: statusText,
    name: row.name
  });

  proxy.$auMessageBox.confirm(msg, t("notice.title")).then(() => {
    const param = {
      ...row,
      openStatus: status === ACTION_TYPE.OFFSHELVE ? 0 : 1
    };
    taskUpd(param).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: t("task_detail.form.status_change_success", {
            status: statusText
          }),
          type: "success"
        });
        getMatData();
      }
    });
  });
};

type ActionType = {
  key: ACTION_TYPE;
  row: TaskListProp | null;
};
const actionClick = ({ key, row }: ActionType) => {
  switch (key) {
    case ACTION_TYPE.EDIT:
    case ACTION_TYPE.TADD:
      taskParam.value.versionId = route.query?.versionId;
      showTaskModal.value = true;
      taskRow.value = row;
      break;
    case ACTION_TYPE.PUTAWAY:
    case ACTION_TYPE.OFFSHELVE:
      handleUpOrDown(row, key);
      break;
    case ACTION_TYPE.DELETE:
      proxy.$auMessageBox
        .confirm(t("task_detail.form.confirm_delete_task"), t("notice.title"))
        .then(() => {
          taskDel({ ids: [row.id] }).then(res => {
            if (res.code === 200) {
              ElMessage({
                message: t("notice.delete_success"),
                type: "success"
              });
              getMatData();
            }
          });
        });
  }
};
// endregion

onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.mat-btn {
  :deep(.btn_) {
    .el-form-item__content {
      justify-content: end;
    }
  }
}

.striped {
  &:nth-child(2n + 1) {
    background: var(--autata-striped-bg-color);
  }
}

.add-btn {
  @apply w-full h-[46px] text-[--el-color-primary] font-[500] text-[14px] disabled:text-[--autata-font-gray-color];

  .iconfont {
    font-size: 14px;
  }
}

.cate {
  width: 100%;
  height: 46px;
  padding-left: 20px;
  margin-right: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 46px;
  color: var(--autata-font-color);
  transition: all 0.3s;

  &.active {
    color: var(--el-color-primary);
    background: var(--autata-hover-bg-color);
  }

  &:hover {
    color: var(--el-color-primary);
    cursor: pointer;
    background: var(--autata-hover-bg-color);
  }
}

body .cate-left {
  :deep(.scroll-height) {
    height: calc(100vh - 35vmin);
  }
}
</style>
